package com.alipay.rebate.shop.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.alipay.rebate.shop.constants.RequestConstant;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.ResultGenerator;
import com.alipay.rebate.shop.dao.mapper.AppSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.pojo.common.ResponseResult;
import com.alipay.rebate.shop.pojo.user.admin.UpdateUserRequest;
import com.alipay.rebate.shop.pojo.user.admin.UserListResponse;
import com.alipay.rebate.shop.pojo.user.admin.UserPageRequest;
import com.alipay.rebate.shop.pojo.user.customer.UpdateUserStatusReq;
import com.alipay.rebate.shop.service.admin.AdminCustomerUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import com.alipay.rebate.shop.utils.QiniuUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@ResponseBody
public class AdminCustomerUserController {

    private final static Logger logger = LoggerFactory.getLogger(AdminCustomerUserController.class);
    @Autowired
    AdminCustomerUserService userService;
    @Resource
    AppSettingsMapper appSettingsMapper;

    @Resource
    UserMapper userMapper;

    /**
     * 更新用户状态
     * @param
     * @return
     */
    @PutMapping(value = "/admin/updateUserStatus")
    public ResponseResult<Integer> updateUserStatus(@RequestBody UpdateUserStatusReq req){
        logger.debug("Receive id and UpdateUserRequest body from request : {}",req);
        int result = userService.updateUserStatus(req);
        return ResultGenerator.genSuccessResponseResult(result);
    }

    /**
     * 更新用户信息
     * @param updateUserRequest
     * @return
     */
    @PutMapping(value = "/admin/updateUserById", produces = RequestConstant.PRODUCES_APPLICATION_JSON)
    @ResponseBody
    public ResponseResult<Integer> updateUserById(@RequestBody @Valid UpdateUserRequest updateUserRequest){
        logger.debug("Receive id and UpdateUserRequest body from request : {}",updateUserRequest);

        int result = userService.updateUserById(updateUserRequest);
        return ResultGenerator.genSuccessResponseResult(result);

//        String password = updateUserRequest.getPassword();
//        logger.debug("password is : {}",password);
//
//        User user = new User();
//        user.setUserId(updateUserRequest.getUserId());
//        user.setUserNickName(updateUserRequest.getUserNickName());
//        user.setRealName(updateUserRequest.getRealName());
//        user.setAlipayAccount(updateUserRequest.getAlipayAccount());
//        logger.debug("realName is : {}",user.getRealName());
//        logger.debug("AlipayAccount is : {}",user.getAlipayAccount());
//        if (StringUtils.isEmpty(user.getRealName()) || StringUtils.isEmpty(user.getAlipayAccount())){
//            userMapper.updateUserAlipayAccount(user.getUserId(),user.getRealName(),user.getAlipayAccount());
//        }
//        Optional.ofNullable(updateUserRequest.getUserRegisterTime()).ifPresent(registerTime -> {
//            user.setUserRegisterTime(new Date(updateUserRequest.getUserRegisterTime()));
//        });
//        user.setUserRegisterIp(updateUserRequest.getUserRegisterIp());
//        user.setUserAmount(updateUserRequest.getUserAmount());
//        user.setUserIntgeralTreasure(updateUserRequest.getUserIntgeralTreasure());
//        user.setUserIntgeral(updateUserRequest.getUserIntgeral());
//        user.setPhone(updateUserRequest.getPhone());
//        user.setParentUserId(updateUserRequest.getParentUserId());
//        if (!StringUtils.isEmpty(updateUserRequest.getUserPassword())) {
//            user.setUserPassword(EncryptUtil.encryptPassword(updateUserRequest.getUserPassword()));
//        }
//        user.setUserStatus(updateUserRequest.getUserStatus());
//        user.setUserGradeId(updateUserRequest.getUserGradeId());
//
//        if(password==null) {
//            int result = userService.update(user);
//            return ResultGenerator.genSuccessResponseResult(result);
//        }else{
//            String pwd = EncryptUtil.encryptPassword(password);
//            String selectPassword = appSettingsMapper.selectPassword();
//            logger.debug("selectPassword is : {}", selectPassword);
//            if (selectPassword.equals(pwd)){
//                int result = userService.update(user);
//                return ResultGenerator.genSuccessResponseResult(result);
//            }else{
//                throw new RuntimeException("校验密码输入错误");
//            }
//        }

    }


    /**
     * 增添新用户
     * @param user
     * @return
     */
    @PostMapping(value = "/admin/insertUser", produces = RequestConstant.PRODUCES_APPLICATION_JSON)
    @ResponseBody
    public Long insertUser(@RequestBody User user){
        return userService.insert(user);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping(value = "/admin/deleteUserById/{id}", produces = RequestConstant.PRODUCES_APPLICATION_JSON)
    @ResponseBody
    public ResponseResult<Integer> deleteUserById(@PathVariable("id") Long id){
        logger.debug("userId is : {}",id);
        int result = userService.delete(id);
        return ResultGenerator.genSuccessResponseResult(result);
    }

    /**
     * 根据条件查询用户信息
     * @param userPageRequest
     * @return
     */
    @GetMapping(value = "/admin/selectUserByCondition",produces = RequestConstant.PRODUCES_APPLICATION_JSON)
    @ResponseBody
    public ResponseResult<PageInfo<UserListResponse>>  selectUserByCondition(UserPageRequest userPageRequest){
        logger.debug("Received UserPageRequest request: {}",userPageRequest);
        PageInfo<UserListResponse> data = userService.searchUserByCondition(userPageRequest);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    /**
     *
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping(value = "/admin/getUserById/{id}", produces = RequestConstant.PRODUCES_APPLICATION_JSON)
    @ResponseBody
    public ResponseResult<User> getUserById(@PathVariable("id") Long id){
        logger.debug("Received id from request: {}",id);
        User user = userService.get(id);
        if(user == null){
            throw  new BusinessException(StatusCode.USER_NOT_EXISTS);
        }
        user.setUserPassword(null);
        user.setOpenId(null);
        return  ResultGenerator.genSuccessResponseResult(user);
    }

//    /**
//     * 后台用户登陆
//     * @return
//     */
//    @PostMapping("/adminLogin")
//    @ResponseBody
//    public ResponseResult adminLogin(
//            @RequestBody @Valid
//            AccountLoginRequest accountLoginRequest,
//            HttpServletResponse response){
//        // 获取主题信息
//        Subject subject = SecurityUtils.getSubject();
//        logger.debug("Login subject is : {}",subject);
//        logger.debug("Login AccountLoginRequest is : {}",accountLoginRequest);
//        UserDto userDto = new UserDto();
//        userDto.setAccount(accountLoginRequest.getAccount());
//        userDto.setPassword(accountLoginRequest.getPassword().toCharArray());
//        // 后台账号密码登陆
//        return userService.adminLogin(userDto,response,subject);
//    }

    @GetMapping("/admin/getQiNiuYunUploadToken")
    @ResponseBody
    public ResponseResult<String> getQiNiuYunUploadToken(){
        String token = QiniuUtil.getQiniuUploadToken();
        return ResultGenerator.genSuccessResponseResult(token);
    }

    @RequestMapping("/admin/cancelTaobaoAuth/{id}")
    @ResponseBody
    public ResponseResult cancelTaobaoAuth(@PathVariable("id") Long id){
        userService.cancelTaobaoAuth(id);
        return ResultGenerator.genSuccessResponseResult();
    }

    @PutMapping("/admin/uploadPictureToQiNui")
    @ResponseBody
    public ResponseResult uploadPictureToQiNui(String localFilePath){
        QiniuUtil.uploadPictureToQiNui(localFilePath);
        return ResultGenerator.genSuccessResponseResult();
    }
    @DeleteMapping("/admin/deleteQiNuiPicture")
    public ResponseResult deleteQiNuiPicture(String key){
        QiniuUtil.deleteQiNuiPicture(key);
        return ResultGenerator.genSuccessResponseResult();
    }

    @GetMapping("/admin/selectTheBlacklist")
    @ResponseBody
    public ResponseResult selectTheBlacklist(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer size,
                                             Long userId,String phone,String userName){
        PageHelper.startPage(page,size);
        List<User> users = userMapper.selectTheBlacklist(userId, phone, userName);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return ResultGenerator.genSuccessResponseResult(pageInfo);
    }
}
